package com.yjps.system.service;

import com.yjps.common.page.Pager;
import com.yjps.system.dao.CodeTypeDao;
import com.yjps.system.model.CodeType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by jessy on 2015/8/22.
 */
@Service
public class CodeTypeService {

    Logger log = LoggerFactory.getLogger(CodeTypeService.class);

    @Autowired
    CodeTypeDao codetypeDao;

    public CodeType findCodeTypeByName(String name){
        Map<String,Object> params = new HashMap<>();
        String hql = "from CodeType t where t.codetypeName =:codetypeName";
        params.put("codetypeName",name);
        return codetypeDao.findUniqueResult(hql,params);
    }

    public CodeType findCodeType(int id) {
        return codetypeDao.load(id);
    }

    public List<CodeType> codetypeList() {
        String hql = "from CodeType c where c.isValid = 1";
        return codetypeDao.find(hql);
    }



    @Transactional
    public int addCodeType(CodeType codetype) {
        return codetypeDao.save(codetype);
    }

    @Transactional
    public CodeType updateCodeType(CodeType codeType) {
        String hql = "update CodeType c set c.codetypeName =:codetypeName,c.codetypeDescription =:codetypeDescription,c.codetypeState =:codetypeState where c.id =:id";
        Map<String, Object> map = new HashMap<>();
        map.put("codetypeName",codeType.getCodetypeName());
        map.put("codetypeDescription",codeType.getCodetypeDescription());
        map.put("codetypeState",codeType.getCodetypeState());
        map.put("id",codeType.getId());
        codetypeDao.excute(hql, map);
        return codetypeDao.load(codeType.getId());
    }

    @Transactional
    public void deleteCodeType(int id) {
        String hql = "update CodeType r set r.isValid = 0 where r.id = :id";
        Map<String,Object> parames = new HashMap<>();
        parames.put("id",id);
        codetypeDao.excute(hql,parames);
        log.debug("delete the Resume success, id is " + id);
    }

    public Pager<CodeType> getUserByPager(Pager<CodeType> pager) throws Exception {
        Map<String, Object> params = new HashMap<>();
        String queryString = "from CodeType t where t.isValid = 1";
        queryString += " order by t.id desc";
        List<CodeType> accounts = codetypeDao.findWithSelect(queryString, params, (pager.getPageNo()-1)*pager.getPageSize(), pager.getPageSize());
        pager.setCount(codetypeDao.getTotalCount(queryString, params));
        pager.setList(accounts);
        return pager;
    }

}
